package org.example.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.example.aop.UserLoginToken;
import org.example.config.UserContextConfig;
import org.example.controller.viewobject.invitationVO;
import org.example.dataobject.CommentDO;
import org.example.error.BusinessException;
import org.example.error.EmBusinessError;
import org.example.response.CommonReturnType;
import org.example.service.InvitationService;
import org.example.service.model.UserModel;
import org.example.service.model.invitation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author xietl
 * @date 2025/8/26  14:48
 * @description 帖子的控制层
 */

@RestController
@RequestMapping("/invitation")
public class invitationController {
    @Autowired
    private InvitationService invitationService;
    @Autowired
    private HttpServletRequest httpServletRequest;

    private static final Logger LOGGER = LoggerFactory.getLogger(invitationController.class);

    @UserLoginToken
    @RequestMapping(value = "/createInvitation",method = RequestMethod.POST)
    public CommonReturnType createInvitation(@Valid @RequestBody invitation invitation) throws BusinessException {

        //从userContext中获取登录用户信息
        UserModel user = UserContextConfig.getUserModel();
        if (user == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,EmBusinessError.USER_NOT_LOGIN.getErrMsg());
        }
        invitation.setCreateTime(new Date());
        invitation.setUserName(user.getName());
        invitation.setViewCount(0);
        invitation.setCommentCount(0);
        invitation.setLikeCount(0);
        invitationService.createInvitation(invitation);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/queryInvitationDetail",method = RequestMethod.GET)
    public CommonReturnType queryInvitationDetail(@RequestParam("postid") int postid) throws BusinessException {
        invitation invitation = invitationService.queryInvitationDetail(postid);
        invitationVO invitationVO = new invitationVO();
        BeanUtils.copyProperties(invitation,invitationVO);
        return CommonReturnType.create(invitationVO);
    }

    @UserLoginToken
    @RequestMapping(value = "/deleteInvitation",method = RequestMethod.POST)
    public CommonReturnType deleteInvitation(@RequestParam("postid") int postid) throws BusinessException {
        invitationService.deleteInvittion(postid,httpServletRequest);
        return CommonReturnType.create(null);
    }
    @UserLoginToken
    @RequestMapping(value = "/updateInvitation",method = RequestMethod.POST)
    public CommonReturnType updateInvitation(invitationVO invitationVO) throws BusinessException {
        invitation invitation = new invitation();
        BeanUtils.copyProperties(invitationVO,invitation);
        invitationService.updateInvitation(invitation);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/queryInvitationList",method = RequestMethod.GET)
    public CommonReturnType queryInvitationList(@RequestParam(value = "fig", defaultValue = "按点赞量排序") String fig) throws BusinessException {
        List<invitation> invitationList = invitationService.queryInvitationsBySort(fig);
        if(invitationList.isEmpty()){
            throw new BusinessException(EmBusinessError.POST_NOT_EXISTING,EmBusinessError.POST_NOT_EXISTING.getErrMsg());
        }
        List<invitationVO> invitationVOList = invitationList.stream().map(invitation -> {
            invitationVO invitationVO = new invitationVO();
            BeanUtils.copyProperties(invitation,invitationVO);
            return invitationVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(invitationVOList);
    }

    @RequestMapping(value = "/queryInvitationListByUsername",method = RequestMethod.GET)
    public CommonReturnType queryInvitationListByUsername(@RequestParam("username") String username) throws BusinessException {
        List<invitation> invitationList = invitationService.queryInvtatonsByusername(username);
        if(invitationList.isEmpty()){
            throw new BusinessException(EmBusinessError.POST_NOT_EXIST, EmBusinessError.POST_NOT_EXIST.getErrMsg());
        }
        List<invitationVO> invitationVOList = invitationList.stream().map(invitation -> {
            invitationVO invitationVO = new invitationVO();
            BeanUtils.copyProperties(invitation,invitationVO);
            return invitationVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(invitationVOList);
    }
    @RequestMapping(value = "/queryInvitationListByCategoryName",method = RequestMethod.GET)
    public CommonReturnType queryInvitationListByCategoryName(@RequestParam("categoryname") String categoryname) throws BusinessException {
        List<invitation> invitationList = invitationService.queryInvtationsBycategoryname(categoryname);
        if(invitationList.isEmpty()){
            throw new BusinessException(EmBusinessError.POST_NOT_EXIST, EmBusinessError.POST_NOT_EXIST.getErrMsg());
        }
        List<invitationVO> invitationVOList = invitationList.stream().map(invitation -> {
            invitationVO invitationVO = new invitationVO();
            BeanUtils.copyProperties(invitation,invitationVO);
            return invitationVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(invitationVOList);
    }

    @RequestMapping(value = "/queryInvitationListByTitleWord",method = RequestMethod.GET)
    public CommonReturnType queryInvitationListByTitleWord(@RequestParam("titleWord") String titleWord) throws BusinessException {
        List<invitation> invitationList = invitationService.queryInvtationsBytitleWord(titleWord);
        if(invitationList.isEmpty()){
            throw new BusinessException(EmBusinessError.POST_NOT_EXIST, EmBusinessError.POST_NOT_EXIST.getErrMsg());
        }
        List<invitationVO> invitationVOList = invitationList.stream().map(invitation -> {
            invitationVO invitationVO = new invitationVO();
            BeanUtils.copyProperties(invitation,invitationVO);
            return invitationVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(invitationVOList);
    }
    /**
     * 点赞帖子（乐观锁方式，推荐使用）
     * 解决多用户并发点赞问题，采用最终一致性方案
     */
    @UserLoginToken
    @RequestMapping(value = "/likeInvitationOptimistic", method = RequestMethod.POST)
    public CommonReturnType likeInvitationOptimistic(@RequestParam("postid") int postid) throws BusinessException {
        int result = invitationService.likeInvitationOptimistic(postid, httpServletRequest);
        return CommonReturnType.create(result);
    }

    /**
     * 取消点赞帖子（乐观锁方式，推荐使用）
     */
    @UserLoginToken
    @RequestMapping(value = "/unlikeInvitationOptimistic", method = RequestMethod.POST)
    public CommonReturnType unlikeInvitationOptimistic(@RequestParam("postid") int postid) throws BusinessException {
        int result = invitationService.unlikeInvitationOptimistic(postid, httpServletRequest);
        return CommonReturnType.create(result);
    }

    /**
     * 经行评论
     * @param postid
     * @param commentContent
     * @return
     * @throws BusinessException
     */
    @UserLoginToken
    @RequestMapping(value = "/addCommentandReturn",method = RequestMethod.POST)
    public CommonReturnType addCommentandReturn(@RequestParam("postid") int postid, @RequestParam("commentContent") String commentContent) throws BusinessException {
         // 参数校验
         if (postid <= 0) {
             throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "帖子ID不能为空");
         }

         if (commentContent == null || commentContent.trim().isEmpty()) {
             throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "评论内容不能为空");
         }
         if (commentContent.length() > 500) {
             throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "评论内容不能超过500字符");
         }
        CommentDO comment = invitationService.addComment(postid, commentContent, httpServletRequest);
        return CommonReturnType.create(comment);
    }

    @UserLoginToken
    @RequestMapping(value = "getCommentsByPostId",method = RequestMethod.GET)
    public CommonReturnType getCommentsByPostId(@RequestParam("postid") int postid) throws BusinessException {
        List<CommentDO> commentDOList = invitationService.getCommentsByPostId(postid);

        return CommonReturnType.create(commentDOList);
    }
    @UserLoginToken
    @RequestMapping(value = "deleteComment",method = RequestMethod.POST)
    public CommonReturnType deleteComment(@RequestParam("commentid") int commentid) throws BusinessException {
        int result = invitationService.deleteComment(commentid,httpServletRequest);
        return CommonReturnType.create(result);
    }

    /**
     * 主动失效指定帖子的评论缓存————刷新缓存，有什么用？ 当帖子的评论发生变化时，需要刷新缓存，确保用户获取到最新的评论数据。
     * @param postId 帖子ID
     * @return 操作结果
     */
    @UserLoginToken
    @RequestMapping(value = "/invalidateCommentCache", method = RequestMethod.POST)
    public CommonReturnType invalidateCommentCache(@RequestParam("postId") int postId) {
        try {
            LOGGER.info("开始失效帖子 {} 的评论缓存", postId);
            invitationService.invalidateCommentCache(postId);
            LOGGER.info("帖子 {} 的评论缓存失效完成", postId);
            return CommonReturnType.create("缓存失效成功");
        } catch (Exception e) {
            LOGGER.error("失效帖子 {} 的评论缓存时发生异常", postId, e);
            return CommonReturnType.create("缓存失效失败: " + e.getMessage(), "fail");
        }
    }



}
